#include "StdAfx.h"
#include "ServerMessageFactory.h"
#include <boost/algorithm/string.hpp>
#include <boost/make_shared.hpp>
#include "ShipsArrivedInfo.h"
#include "ServerShipsLaunchedMessage.h"
#include "ServerShipsArrivedMessage.h"

template<typename Iter>
ShipsArrivedInfoPtr ParseShipsArrivedInfo(Iter begin, Iter end)
{
   if (*begin++ != "DstPlanet")
   {
      throw std::exception("ParseShipsArrivedInfo wrong message format(DstPlanet)");
   }

   PlanetID planetID = PlanetID(atoi((begin++)->c_str()));

   if (*begin++ != "CountOfShips")
   {
      throw std::exception("ParseShipsArrivedInfo wrong message format(CountOfShips)");
   }

   unsigned int countOfShips = unsigned(atoi((begin++)->c_str()));

   if (*begin++ != "PlayerOwnerID")
   {
      throw std::exception("ParseShipsArrivedInfo wrong message format(PlayerOwnerID)");
   }

   PlayerID playerID = PlayerID(atoi((begin++)->c_str()));

   ShipsArrivedInfoPtr shipsArrivedInfoPtr = boost::make_shared<ShipsArrivedInfo>(planetID, countOfShips, playerID);

   return shipsArrivedInfoPtr;
}

ServerMessageFactory::ServerMessageFactory(GalconRoom& galconRoom, const ServerParticipantPtr serverParticipant)
   : m_galconRoom(galconRoom)
   , m_serverParticipant(serverParticipant)
{

}

ServerMessageFactory::~ServerMessageFactory(void)
{
}

MessageBasePtr ServerMessageFactory::do_parseMessage( MessagesEnum messageType, split_vector_type_iter begin, split_vector_type_iter end)
{
   switch (messageType)
   {
   case ShipsLaunched:
      {
         return buildShipsLaunchedMessage(begin, end);
      }
      break;
   case ShipsArrived:
      {
         return buildShipsArrivedMessage(begin, end);
      }
      break;
   default:
      {
         throw std::exception("ServerMessageFactory: wrong message type in ParseMessage");
      }
      break;
   }
}


template<typename Iter>
MessageBasePtr ServerMessageFactory::buildShipsLaunchedMessage( Iter begin, Iter end)
{
   FlightInfoPtr flightInfoPtr = ParseShipsLaunched(begin,end);
   MessageBasePtr message = boost::make_shared<ServerShipsLaunchedMessage>(boost::ref(m_galconRoom), flightInfoPtr, m_serverParticipant);
   return message;   
}

template<typename Iter>
MessageBasePtr ServerMessageFactory::buildShipsArrivedMessage( Iter begin, Iter end)
{
   ShipsArrivedInfoPtr shipsArrivedInfoPtr = ParseShipsArrivedInfo(begin, end);
   MessageBasePtr message = boost::make_shared<ServerShipsArrivedMessage>(boost::ref(m_galconRoom), shipsArrivedInfoPtr);
   return message;
}